package cn.xfdzx.android.apps.shop.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.caller.BankABCCaller;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.login.OneLoginMainActivity;
import cn.xfdzx.android.apps.shop.adapter.ConfirmOrderGoodsAdapter;
import cn.xfdzx.android.apps.shop.adapter.SelectAddressRetailAdapter;
import cn.xfdzx.android.apps.shop.adapter.SelectMapLVAdapter;
import cn.xfdzx.android.apps.shop.adapter.SelectOutStockLVAdapter;
import cn.xfdzx.android.apps.shop.adapter.SelectTimeDayLVAdapter;
import cn.xfdzx.android.apps.shop.adapter.SelectTimeLVAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.AddressListBeen;
import cn.xfdzx.android.apps.shop.bean.ConfirmGoodBeen;
import cn.xfdzx.android.apps.shop.bean.DeleteAddressBeen;
import cn.xfdzx.android.apps.shop.bean.LogisticsBeen;
import cn.xfdzx.android.apps.shop.bean.NewOrderBeen;
import cn.xfdzx.android.apps.shop.contract.ConfirmRetailContract;
import cn.xfdzx.android.apps.shop.contract.ItemClickListener;
import cn.xfdzx.android.apps.shop.evenbus.CarInitDataMessage;
import cn.xfdzx.android.apps.shop.evenbus.OrderMoneyMessage;
import cn.xfdzx.android.apps.shop.presenter.ConfirmRetailPresenter;
import cn.xfdzx.android.apps.shop.util.DensityUtils;
import cn.xfdzx.android.apps.shop.util.KeybordUtil;
import cn.xfdzx.android.apps.shop.util.PayResult;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.ShopCarPopupWindow;
import cn.xfdzx.android.apps.shop.util.SoftKeyBoardListener;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.TransBaiduGaodePoint;
import cn.xfdzx.android.apps.shop.util.Util;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;
import cn.xfdzx.android.apps.shop.view.SlideRecyclerView;

import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;
import static cn.xfdzx.android.apps.shop.activity.MapDistributionActivity.drawableToBitmap;
import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;
import static cn.xfdzx.android.apps.shop.apps.Constants.START_CODE;
import static cn.xfdzx.android.apps.shop.apps.Constants.WX_APP_ID;

/**
 * 确认订单
 */
public class ConfirmOrderActivity extends BaseMvpActivity<ConfirmRetailPresenter> implements ConfirmRetailContract.View {

    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.tv_out_of_stock_content)
    TextView tvOutOfStockContent;
    @BindView(R.id.iv_number_privacy_bg)
    ImageView ivNumberPrivacyBg;
    @BindView(R.id.iv_number_privacy_left)
    ImageView ivNumberPrivacyLeft;
    @BindView(R.id.iv_number_privacy_right)
    ImageView ivNumberPrivacyRight;
    @BindView(R.id.tv_distribution)
    TextView tvDistribution;
    @BindView(R.id.tv_ziti)
    TextView tvZiti;
    @BindView(R.id.tv_big_distribution)
    TextView tvBigDistribution;
    @BindView(R.id.tv_big_ziti)
    TextView tvBigZiti;
    @BindView(R.id.ll_select_address)
    LinearLayout llSelectAddress;
    @BindView(R.id.ll_delivery_time)
    LinearLayout llDeliveryTime;
    @BindView(R.id.rl_shop_ziti)
    RelativeLayout rlShopZiti;
    @BindView(R.id.rl_user_address)
    RelativeLayout rlUserAddress;
    @BindView(R.id.rl_distribution_price)
    RelativeLayout rlDistributionPrice;//配送费一行
    //    @BindView(R.id.tv_distribution_price)
//    TextView tvDistributionOldPrice;
    @BindView(R.id.tv_to_pay)
    TextView tvToPay;
    @BindView(R.id.tv_note_content)
    TextView tvNoteContent;
    @BindView(R.id.tv_store_name)
    TextView tvStoreName;
    @BindView(R.id.iv_weixin_select)
    ImageView ivWeixinSelect;
    @BindView(R.id.iv_zhifubao_select)
    ImageView ivZhifubaoSelect;
    @BindView(R.id.iv_nong_hang_select)
    ImageView ivNongHangSelect;
    @BindView(R.id.rl_ziti_time)
    RelativeLayout rlZitiTime;
    @BindView(R.id.rv_goods)
    RecyclerView rvGoods;
    @BindView(R.id.tv_more_pack_up)
    TextView tvMorePackUp;
    @BindView(R.id.tv_temporarily_no_use)
    TextView tvTemporarilyNoUse;
    @BindView(R.id.ll_state)
    LinearLayout llState;
    @BindView(R.id.tv_address_tag)
    TextView tvAddressTag;
    @BindView(R.id.tv_address_info)
    TextView tvAddressInfo;
    @BindView(R.id.tv_user_info)
    TextView tvUserInfo;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_yi_preferential)
    TextView tvYiPreferential;
    @BindView(R.id.tv_total_freight)
    TextView tvTotalFreight;
    @BindView(R.id.tv_pay_total_money)
    TextView tvPayTotalMoney;
    @BindView(R.id.tv_immediately_time)
    TextView tvImmediatelyTime;//选择时间
    @BindView(R.id.tv_ziti_time)
    TextView tvZitiTime;//选择时间
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;//门店名称
    @BindView(R.id.tv_shop_address)
    TextView tvShopAddress;//门店名称
    @BindView(R.id.tv_total)
    TextView tvTotal;//配送费说明
    @BindView(R.id.ett_phone)
    EditText ettPhone;//门店预留手机号
    @BindView(R.id.map_ziti_view)
    MapView map;

    @BindView(R.id.rl_desover)
    RelativeLayout rl_desover;//超重布局
    @BindView(R.id.tv_orerweight_fee)
    TextView tv_orerweight_fee;//超重费
    @BindView(R.id.tv_desorerweight)
    TextView tv_desorerweight;//超重费说明
    @BindView(R.id.tv_deslogic)
    TextView tv_deslogic;//距离运费
    @BindView(R.id.tv_desweight)
    TextView tv_desweight;//基础重量
    @BindView(R.id.tv_basefee)
    TextView tv_basefee;//基础运费

    AMap aMap;//初始化地图控制器对象

    private ShopCarPopupWindow select_address_PW;
    private ShopCarPopupWindow select_time_PW;
    private ShopCarPopupWindow select_out_stock_PW;
    private ShopCarPopupWindow select_Map_PW;
    private ShopCarPopupWindow couponPopupWindow;

    private ArrayList<ConfirmGoodBeen.DataBean.CartInfoBean.GoodsBean> list = new ArrayList<>();
    private ConfirmOrderGoodsAdapter confirmOrderGoodsAdapter;
    private boolean is_more_pack_up = false;//收起

    private RelativeLayout.LayoutParams item_bar;
    private ConfirmGoodBeen.DataBean dataBean;
    private Context mContext;

    private AddressListBeen.DataBean dataAddressInfo;//选择的地址信息
    private String address_id = "";
    private SelectAddressRetailAdapter selectAddressRetailAdapter;
    private List<AddressListBeen.DataBean> addressList = new ArrayList();
    private String pay_type = "weixin";
    private String delivery_method = "1";//配送方式 1配送 2自提
    private String order_express_type = "1"; //'1-今日2-明日3-后日'
    private List<String> dayList = new ArrayList<String>();

    private IWXAPI api;
    private Marker mLocMarker;

    private boolean isCanSubmitOrder;//是否可以支付
    private String submitOrderErrorMessage;//错误信息
    private LinearLayout llAddressHint;
    private SlideRecyclerView rv_address;
    private ArrayList<String> selectMaps = new ArrayList<>();
    //private Dialog dialog_peisong;
    private Dialog dialog_note;
    private EditText ettNote;
    private TextView tvNoteNum;
    private String paymentPrice;//应付总价
    private int allcount;//所有数量
    private boolean isMore;


    @Override
    public int getLayoutId() {
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID);
        return R.layout.activity_confirm_order;
    }

    @Override
    public void initView() {
        mContext = ConfirmOrderActivity.this;
        dayList.add("今天");
        //原来的配送费
//        tvDistributionOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        initHigh();
        StatusBarUtil.setLightStatusBar(this, false, true);
        mPresenter = new ConfirmRetailPresenter();
        mPresenter.attachView(this);

        dataBean = (ConfirmGoodBeen.DataBean) getIntent().getSerializableExtra("confirm");


        isCanSubmitOrder = dataBean.isIs_can_submit_order();
        submitOrderErrorMessage = dataBean.getSubmit_order_error_message();
        default_view();
        list.clear();
        if (dataBean.getCartInfo().size() != 0) {
            if (dataBean.getCartInfo().get(0).getStore().getIs_self_extracting() == 0) {
                llTitle.setVisibility(View.GONE);
                llSelectAddress.setBackgroundResource(R.drawable.confirm_order_title_bg_white);
                rlUserAddress.setBackgroundResource(R.drawable.confirm_order_title_bg_white);
            }

            list.addAll(dataBean.getCartInfo().get(0).getGoods());
            double totalPrice = 0;
            allcount = 0;
            for (ConfirmGoodBeen.DataBean.CartInfoBean.GoodsBean goodsBean : list) {
                totalPrice = Utils.addDouble(totalPrice, Utils.mul(Double.parseDouble(goodsBean.getMarketPrice()), goodsBean.getCart_num()));
                allcount += goodsBean.getCart_num();
            }
            double b = Utils.subDouble(Double.parseDouble(dataBean.getPriceGroup().getPaymentPrice()), Double.parseDouble(dataBean.getPriceGroup().getStorePostage()));
            totalPrice = Utils.subDouble(totalPrice, b);
            tvYiPreferential.setText("¥" + totalPrice);

            tvStoreName.setText(dataBean.getCartInfo().get(0).getStore().getOffline_shop_name());
            if (dataBean.getCartInfo().get(0).getGoods().size() > 2) {
                isMore = true;
                tvMorePackUp.setVisibility(View.VISIBLE);
                tvMorePackUp.setText("共" + allcount + "件 " + getResources().getText(R.string.an_more));
                Drawable nav_up = getResources().getDrawable(R.drawable.icon_location_down);
                nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());

                tvMorePackUp.setCompoundDrawables(null, null, nav_up, null);
            } else {
                isMore = false;
                tvMorePackUp.setVisibility(View.VISIBLE);
                tvMorePackUp.setText("共" + allcount + "件");
                tvMorePackUp.setCompoundDrawables(null, null, null, null);
            }

        confirmOrderGoodsAdapter = new ConfirmOrderGoodsAdapter(this, list,dataBean.getCartInfo().get(0).getStore().getId());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvGoods.setLayoutManager(linearLayoutManager);
        rvGoods.setItemAnimator(new DefaultItemAnimator());
        rvGoods.setNestedScrollingEnabled(false);
        rvGoods.setAdapter(confirmOrderGoodsAdapter);

        }

        setSoftKeyBoardListener();
        addMarkerInScreenCenter();
        ivNumberPrivacyBg.setTag(true);

        if (new File("/data/data/com.baidu.BaiduMap").exists()) {
            selectMaps.add("com.baidu.BaiduMap");
        }
        if (new File("/data/data/com.autonavi.minimap").exists()) {
            selectMaps.add("com.autonavi.minimap");
        }
        if (new File("/data/data/com.tencent.map").exists()) {
            selectMaps.add("com.tencent.map");
        }
    }


    private void addMarkerInScreenCenter() {
        if (aMap == null) {
            aMap = map.getMap();
        }
        if (null != dataBean.getCartInfo()) {
            LatLng latLng = new LatLng(Double.parseDouble(dataBean.getCartInfo().get(0).getStore().getLat()), Double.parseDouble(dataBean.getCartInfo().get(0).getStore().getLng()));

            //设置地图的放缩级别
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
            aMap.getUiSettings().setZoomControlsEnabled(false);
            aMap.getUiSettings().setZoomGesturesEnabled(false);
            aMap.getUiSettings().setScrollGesturesEnabled(false);
            aMap.setCustomMapStyle(
                    new com.amap.api.maps.model.CustomMapStyleOptions()
                            .setEnable(true)
                            .setStyleId("3b7df2aeffe4f90411241e09282a2cfa")//官网控制台-自定义样式 获取
            );
//            MarkerOptions markerOptions = new MarkerOptions();
//            markerOptions.position(latLng);
//            markerOptions.title(dataBean.getCartInfo().get(0).getStore().getOffline_shop_name());
//            markerOptions.snippet(dataBean.getCartInfo().get(0).getStore().getMobile());
//            markerOptions.visible(true);
            RoundedCorners roundedCorners = new RoundedCorners(10);
            //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
//        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
            RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(DensityUtils.dip2px(this, 44), DensityUtils.dip2px(this, 44));

            Glide.with(this)
                    .load(dataBean.getCartInfo().get(0).getStore().getLogo()).apply(options.transform(new CircleCrop(), roundedCorners)).into(new SimpleTarget<Drawable>() {
                @Override
                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                    Bitmap bitmap = drawableToBitmap(resource);
                    BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
                    aMap.addMarker(new MarkerOptions()
                            .position(latLng)
                            .icon(bitmapDescriptor));
                }
            });

//            BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_shop_logo_ziti));
//            markerOptions.icon(bitmapDescriptor);
//            aMap.addMarker(markerOptions);
//            mLocMarker.setAnchor(0.5f, 1.0f);
//            Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
//            mLocMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
//            mLocMarker.setPosition(latLng);
//        marker.setPosition(latLng);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        map.onCreate(savedInstanceState);
        //初始化地图控制器对象

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);

    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        map.onResume();
        String param = getIntent().getStringExtra("from_bankabc_param");
        if (param != null) {

            param = param.substring(param.indexOf("STT="), param.length());
            String result = param.substring(4, param.indexOf("&"));
            Log.e("支付结果", "param===" + result);
            if ("0000".equals(result)) {
                //支付成功
                intent = new Intent(this, MainActivity.class);
                intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(FLAG_ACTIVITY_SINGLE_TOP);
                intent.putExtra("from", "pay");
                startActivity(intent);
                return;
            } else if ("9999".equals(result)) {
                Utils.toastMessage(this, "支付未完成");


            } else if ("PA500401".equals(result)) {
                Utils.toastMessage(this, "已存在成功支付的订单");
            } else {
                Utils.toastMessage(this, "支付出错");
            }
            intent = new Intent(this, MainActivity.class);
            intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(FLAG_ACTIVITY_SINGLE_TOP);
            intent.putExtra("from", "pay_cancel");
            startActivity(intent);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        map.onPause();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        map.onSaveInstanceState(outState);
    }

    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
    }

    private void default_view() {
        ettPhone.setEnabled(false);
        tvShopName.setText(dataBean.getCartInfo().get(0).getStore().getOffline_shop_name());
        tvShopAddress.setText(dataBean.getCartInfo().get(0).getStore().getAddress());
        if (null != dataBean.getDeliveryTimeList()) {
            if (null != dataBean.getDeliveryTimeList().getSameDay()) {
                if (dataBean.getDeliveryTimeList().getSameDay().size() != 0) {
                    tvImmediatelyTime.setText(dataBean.getDeliveryTimeList().getSameDay().get(0).getDeliveryTime());
                    tvZitiTime.setText(dataBean.getDeliveryTimeList().getSameDay().get(0).getDeliveryTime());
                }
            }
        }
        tvBigDistribution.setVisibility(View.VISIBLE);
        tvBigZiti.setVisibility(View.INVISIBLE);
        if (null != dataBean.getAddressInfo()) {
            rlUserAddress.setVisibility(View.VISIBLE);
            llSelectAddress.setVisibility(View.GONE);
            if (dataBean.getAddressInfo().getLabel() == 1) {
                tvAddressTag.setText("家");
            } else if (dataBean.getAddressInfo().getLabel() == 2) {
                tvAddressTag.setText("公司");
            } else if (dataBean.getAddressInfo().getLabel() == 3) {
                tvAddressTag.setText("学校");
            } else {
                tvAddressTag.setVisibility(View.GONE);
            }
            tvAddressInfo.setText(dataBean.getAddressInfo().getAddress_info() + dataBean.getAddressInfo().getHouse_number());
            tvUserInfo.setText(dataBean.getAddressInfo().getRealname() + "        " + dataBean.getAddressInfo().getMobile());
            ettPhone.setText(dataBean.getAddressInfo().getMobile());
            address_id = dataBean.getAddressInfo().getId() + "";
            rlUserAddress.setVisibility(View.VISIBLE);
            llSelectAddress.setVisibility(View.GONE);
        } else {
            rlUserAddress.setVisibility(View.GONE);
            llSelectAddress.setVisibility(View.VISIBLE);
        }
        llDeliveryTime.setVisibility(View.VISIBLE);
        rlShopZiti.setVisibility(View.GONE);
        tvTotalMoney.setText("¥" + dataBean.getPriceGroup().getTotalPrice());
//             tvTotalFreight.setText("¥" + dataBean.getPriceGroup().getStorePostage());
        //配送费显示基础运费+超出距离价格
        tvTotalFreight.setText("¥" + (Double.parseDouble(dataBean.getPriceGroup().getBasicFreight()) +
                Double.parseDouble(dataBean.getPriceGroup().getKilometre_price())));
        Log.e("tvTotalFreight", (Double.parseDouble(dataBean.getPriceGroup().getBasicFreight()) +
                Double.parseDouble(dataBean.getPriceGroup().getKilometre_price())) + "===");
        paymentPrice = "¥" + dataBean.getPriceGroup().getPaymentPrice();
        tvPayTotalMoney.setText(paymentPrice);
        tvTotalMoney.setText("实付:" + paymentPrice);
        tvTotal.setText("(总重" + (int) Double.parseDouble(dataBean.getPriceGroup().getGoods_weight()) + "g)");

//        dialog_peisong = new Dialog(this, R.style.ExitDialog);
//        View layout = View.inflate(this, R.layout.dialog_distribution_text, null);
//        dialog_peisong.setContentView(layout);
//        dialog_peisong.setCanceledOnTouchOutside(true);
//        tvWeightText = layout.findViewById(R.id.tv_weight_text);
//        tvDistance = layout.findViewById(R.id.tv_distance);
//        tvBaseMoney = layout.findViewById(R.id.tv_base_money);
//        tvWeightMoney = layout.findViewById(R.id.tv_weight_money);
//        tvDistanceMoney = layout.findViewById(R.id.tv_distance_money);
//        tvWeightText.setText(dataBean.getPriceGroup().getLogistics_desc().getWeight_text());
//        tvDistance.setText(dataBean.getPriceGroup().getLogistics_desc().getKilometre_text());
//        tvBaseMoney.setText("¥" + dataBean.getPriceGroup().getBasicFreight());
//        tvWeightMoney.setText("¥" + dataBean.getPriceGroup().getWeight_price());
//        tvDistanceMoney.setText("¥" + dataBean.getPriceGroup().getKilometre_price());

        tv_basefee.setText("基础运费" + dataBean.getPriceGroup().getBasicFreight() + "元");
        tv_deslogic.setText(dataBean.getPriceGroup().getLogistics_desc().getKilometre_text());
        tv_desweight.setText(dataBean.getPriceGroup().getLogistics_desc().getWeight_text());
        tv_desorerweight.setText(dataBean.getPriceGroup().getLogistics_desc().getOver_weight_price());
        if (Double.parseDouble(dataBean.getPriceGroup().getWeight_price()) > 0) {
            rl_desover.setVisibility(View.VISIBLE);
            //超重费
            tv_orerweight_fee.setText("¥" + dataBean.getPriceGroup().getWeight_price());
        } else {
            rl_desover.setVisibility(View.GONE);
        }

//        layout.findViewById(R.id.iv_dialog_cancel).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                dialog_peisong.dismiss();
//            }
//        });


        dialog_note = new Dialog(this, R.style.ExitDialog);
        View layout_note = View.inflate(this, R.layout.dialog_note_text, null);
        dialog_note.setContentView(layout_note);
        dialog_note.setCanceledOnTouchOutside(true);
        ettNote = layout_note.findViewById(R.id.ett_note);
        tvNoteNum = layout_note.findViewById(R.id.tv_note_num);
        ettNote.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvNoteNum.setText(s.toString().length() + "/30");

            }
        });
        layout_note.findViewById(R.id.tvw_dialog_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_note.dismiss();
            }
        });
        layout_note.findViewById(R.id.tv_dialog_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_note.dismiss();
                tvNoteContent.setText(ettNote.getText().toString().trim());
                ettNote.getText().clear();

            }
        });

    }

    private TextView tvWeightText;
    private TextView tvDistance;
    private TextView tvBaseMoney;
    private TextView tvWeightMoney;
    private TextView tvDistanceMoney;


    @OnClick({R.id.tv_total, R.id.map_bg, R.id.iv_number_privacy_bg, R.id.iv_ett_phone, R.id.view_phone, R.id.tv_temporarily_no_use, R.id.tv_more_pack_up, R.id.rl_ziti_time, R.id.ll_pay_weixin, R.id.ll_pay_zhifubao, R.id.ll_nonghang, R.id.iv_back, R.id.tv_to_pay, R.id.tv_out_of_stock_content, R.id.tv_note_content, R.id.tv_distribution, R.id.tv_ziti, R.id.ll_select_address, R.id.tv_immediately_time, R.id.rl_user_address})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_total:
//                if (Utils.isFastClick()) {
//                    dialog_peisong.show();
//                }
                break;
            case R.id.map_bg:
                if (selectMaps.size() == 0) {
                    Utils.toastMessage(this, selectMaps.size() + "");
                    return;
                }
                if (select_Map_PW == null) {
                    select_Map_PW = new ShopCarPopupWindow(this, R.layout.pw_select_map);
                    SelectMapLVAdapter selectMapLVAdapter = new SelectMapLVAdapter(mContext, selectMaps);

                    ((ListView) select_Map_PW.getRootView().findViewById(R.id.lv_map)).setAdapter(selectMapLVAdapter);
                    ((ListView) select_Map_PW.getRootView().findViewById(R.id.lv_map)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            select_Map_PW.shareClose();
                            if ("com.baidu.BaiduMap".equals(selectMaps.get(position))) {

                                LatLng sourceLatLng = new LatLng(Double.parseDouble(dataBean.getCartInfo().get(0).getStore().getLat()), Double.parseDouble(dataBean.getCartInfo().get(0).getStore().getLng()));

                                LatLng desLatLng = TransBaiduGaodePoint.gaode_to_baidu(sourceLatLng);
                                Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse("baidumap://map/geocoder?location=" + desLatLng.latitude + "," + desLatLng.longitude));
                                startActivity(intent);
                            } else if ("com.autonavi.minimap".equals(selectMaps.get(position))) {
                                Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse("androidamap://route?sourceApplication=appName&slat=&slon=&sname=我的位置&dlat=" + dataBean.getCartInfo().get(0).getStore().getLat() + "&dlon=" + dataBean.getCartInfo().get(0).getStore().getLng() + "&dname=目的地&dev=0&t=2"));
                                startActivity(intent);
                            } else if ("com.tencent.map".equals(selectMaps.get(position))) {
                                Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse("qqmap://map/routeplan?type=drive&from=&fromcoord=&to=目的地&tocoord=" + dataBean.getCartInfo().get(0).getStore().getLat() + "," + dataBean.getCartInfo().get(0).getStore().getLng() + "&policy=0&referer=appName"));
                                startActivity(intent);
                            }

                        }
                    });
                }
                select_Map_PW.showPopupWindow();
                break;
            case R.id.iv_number_privacy_bg:
                if ((boolean) ivNumberPrivacyBg.getTag()) {
                    ivNumberPrivacyBg.setTag(false);
                    ivNumberPrivacyBg.setImageResource(R.drawable.number_privacy_bg_green);
                    ivNumberPrivacyLeft.setVisibility(View.GONE);
                    ivNumberPrivacyRight.setVisibility(View.VISIBLE);
                } else {
                    ivNumberPrivacyBg.setTag(true);
                    ivNumberPrivacyBg.setImageResource(R.drawable.number_privacy_bg_hui);
                    ivNumberPrivacyLeft.setVisibility(View.VISIBLE);
                    ivNumberPrivacyRight.setVisibility(View.GONE);
                }
                break;
            case R.id.view_phone:
            case R.id.iv_ett_phone:

                ettPhone.setEnabled(true);
                KeybordUtil.showSoftInput(this, ettPhone);
                Selection.setSelection(ettPhone.getText(), ettPhone.getText().toString().length());

                break;
            case R.id.tv_temporarily_no_use:
                Intent intent = new Intent(this, CouponActivity.class);
                startActivity(intent);
//                if (Utils.isFastClick()) {
//                    if (couponPopupWindow != null) {
//
//                    } else {
//                        couponPopupWindow = new ShopCarPopupWindow(this, R.layout.pw_coupon);
//                        couponPopupWindow.getRootView().findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                couponPopupWindow.shareClose();
//
//                            }
//                        });
//                        ((ListView) couponPopupWindow.getRootView().findViewById(R.id.lv_juan)).setAdapter(new CarCouponsLVAdapter(this, new ArrayList<CarCouponsBeen>()));
//                    }
//                    couponPopupWindow.showPopupWindow();
//                }
                break;
            case R.id.tv_more_pack_up:
                if (!isMore) {
                    return;
                }
                if (is_more_pack_up) {
                    confirmOrderGoodsAdapter.is_open = false;
                    confirmOrderGoodsAdapter.notifyDataSetChanged();
                    tvMorePackUp.setText("共" + allcount + "件 " + getResources().getText(R.string.an_more));
                    Drawable nav_up = getResources().getDrawable(R.drawable.icon_confirm_order_more);
                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                    tvMorePackUp.setCompoundDrawables(null, null, nav_up, null);

                } else {
                    confirmOrderGoodsAdapter.is_open = true;
                    confirmOrderGoodsAdapter.notifyDataSetChanged();
                    tvMorePackUp.setText("共" + allcount + "件 " + getResources().getText(R.string.pack_up));
                    Drawable nav_up = getResources().getDrawable(R.drawable.icon_location_on);
                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());

                    tvMorePackUp.setCompoundDrawables(null, null, nav_up, null);

                }
                is_more_pack_up = !is_more_pack_up;
                break;

            case R.id.ll_pay_weixin:
                pay_type = "weixin";
                ivWeixinSelect.setImageResource(R.drawable.icon_select_orange);
                ivZhifubaoSelect.setImageResource(R.drawable.select_pay_type_grey_bg);
                ivNongHangSelect.setImageResource(R.drawable.select_pay_type_grey_bg);
                break;
            case R.id.ll_pay_zhifubao:
                pay_type = "alipay";
                ivWeixinSelect.setImageResource(R.drawable.select_pay_type_grey_bg);
                ivZhifubaoSelect.setImageResource(R.drawable.icon_select_orange);
                ivNongHangSelect.setImageResource(R.drawable.select_pay_type_grey_bg);
                break;
            case R.id.ll_nonghang:
                pay_type = "abcp";
                ivWeixinSelect.setImageResource(R.drawable.select_pay_type_grey_bg);
                ivZhifubaoSelect.setImageResource(R.drawable.select_pay_type_grey_bg);
                ivNongHangSelect.setImageResource(R.drawable.icon_select_orange);
                break;

            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_to_pay:
                if (address_id.isEmpty()) {
                    Toast.makeText(this, "请选择收货地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (isCanSubmitOrder) {
                    //支付完成后显示总价用的

                    EventBus.getDefault().post(new OrderMoneyMessage(paymentPrice, " "));
                    String marks = "";
                    if (delivery_method.equals("1")) {
                        if (tvNoteContent.getText().toString().isEmpty()) {
                            marks = "\"" + dataBean.getCartInfo().get(0).getStore().getId() + "\"" + ":" + "\"" + tvOutOfStockContent.getText().toString() + "\"";
                        } else {
                            marks = "\"" + dataBean.getCartInfo().get(0).getStore().getId() + "\"" + ":" + "\"" + tvNoteContent.getText().toString() + "\\n" + tvOutOfStockContent.getText().toString() + "\"";
                        }
                    } else {
                        marks = "\"" + dataBean.getCartInfo().get(0).getStore().getId() + "\"" + ":" + "\"" + tvNoteContent.getText().toString() + "\"";
                    }
                    marks = "{" + marks + "}";
                    mPresenter.confirmRetail(dataBean.getOrderKey(), "", marks, pay_type, address_id, "今日达", tvImmediatelyTime.getText().toString(), tvImmediatelyTime.getText().toString(), ettPhone.getText().toString(), delivery_method, dataBean.getIs_delivery() + "", order_express_type);
                } else {
                    Utils.toastMessage(mContext, submitOrderErrorMessage);
                }

                break;
            case R.id.tv_out_of_stock_content:
                if (select_out_stock_PW == null) {
                    select_out_stock_PW = new ShopCarPopupWindow(this, R.layout.pw_select_out_stock);
                    select_out_stock_PW.getRootView().findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            select_out_stock_PW.shareClose();
                        }
                    });
                    ArrayList<String> list = new ArrayList<String>();
                    list.add("其它商品继续配送(缺货商品退款）");
                    list.add("缺货时电话与我沟通");

                    SelectOutStockLVAdapter selectOutStockLVAdapter = new SelectOutStockLVAdapter(mContext, list);

                    ((ListView) select_out_stock_PW.getRootView().findViewById(R.id.lv_out_fo_stock)).setAdapter(selectOutStockLVAdapter);
                    ((ListView) select_out_stock_PW.getRootView().findViewById(R.id.lv_out_fo_stock)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            tvOutOfStockContent.setText(list.get(position));
                            selectOutStockLVAdapter.setNowPosition(position);
                            select_out_stock_PW.shareClose();
                        }
                    });
                }
                select_out_stock_PW.showPopupWindow();
                break;
            case R.id.tv_note_content:
                //备注
                dialog_note.show();
                break;
            case R.id.tv_distribution:
                delivery_method = "1";
                rlDistributionPrice.setVisibility(View.VISIBLE);

                tvBigDistribution.setVisibility(View.VISIBLE);
                tvBigZiti.setVisibility(View.INVISIBLE);
                if (null != dataBean.getAddressInfo()) {
                    rlUserAddress.setVisibility(View.VISIBLE);
                    llSelectAddress.setVisibility(View.GONE);
                    if (dataBean.getAddressInfo().getLabel() == 1) {
                        tvAddressTag.setText("家");
                    } else if (dataBean.getAddressInfo().getLabel() == 2) {
                        tvAddressTag.setText("公司");
                    } else if (dataBean.getAddressInfo().getLabel() == 3) {
                        tvAddressTag.setText("学校");
                    } else {
                        tvAddressTag.setVisibility(View.GONE);
                    }
                    tvAddressInfo.setText(dataBean.getAddressInfo().getAddress_info() + dataBean.getAddressInfo().getHouse_number());
                    tvUserInfo.setText(dataBean.getAddressInfo().getRealname() + "        " + dataBean.getAddressInfo().getMobile());
                    ettPhone.setText(dataBean.getAddressInfo().getMobile());

                    address_id = dataBean.getAddressInfo().getId() + "";
                    rlUserAddress.setVisibility(View.VISIBLE);
                    llSelectAddress.setVisibility(View.GONE);
                } else {
                    rlUserAddress.setVisibility(View.GONE);
                    llSelectAddress.setVisibility(View.VISIBLE);
                }
                llDeliveryTime.setVisibility(View.VISIBLE);
                rlShopZiti.setVisibility(View.GONE);
                tvPayTotalMoney.setText(paymentPrice);
                tvTotalMoney.setText("实付:" + paymentPrice);
                break;
            case R.id.tv_ziti:
                delivery_method = "2";
                if (dataBean.getCartInfo().size() != 0) {
                    paymentPrice = "¥" + dataBean.getPriceGroup().getTotalPrice();
                    tvPayTotalMoney.setText(paymentPrice);
                    tvTotalMoney.setText("实付:" + paymentPrice);
                }
                rlDistributionPrice.setVisibility(View.GONE);
                default_ziti();
                break;
            case R.id.rl_user_address:
            case R.id.ll_select_address:
                if (addressList.size() != 0) {
                    select_address_PW.showPopupWindow();
                } else {
                    showAddress();
                    mPresenter.initAddressData("1", 200 + "");
                }
                break;
            case R.id.rl_ziti_time:
            case R.id.tv_immediately_time:
                showTime();
                break;
        }
    }

    private void showTime() {
        if (dataBean.getDeliveryTimeList() == null) {
            Utils.toastMessage(this, "不在配送时间范围内");
            return;
        }
        if (dataBean.getDeliveryTimeList().getSameDay() == null) {
            Utils.toastMessage(this, "不在配送时间范围内");
            return;
        }
        if (select_time_PW == null) {
            select_time_PW = new ShopCarPopupWindow(this, R.layout.pw_select_time);
            select_time_PW.getRootView().findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    select_time_PW.shareClose();
                }
            });
            ((ListView) select_time_PW.getRootView().findViewById(R.id.lv_day)).setAdapter(new SelectTimeDayLVAdapter(this, dayList));
            SelectTimeLVAdapter selectTimeLVAdapter = new SelectTimeLVAdapter(mContext, dataBean.getDeliveryTimeList().getSameDay());
            ((ListView) select_time_PW.getRootView().findViewById(R.id.lv_time)).setAdapter(selectTimeLVAdapter);
            ((ListView) select_time_PW.getRootView().findViewById(R.id.lv_time)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    selectTimeLVAdapter.now_position = position;
                    tvImmediatelyTime.setText(dataBean.getDeliveryTimeList().getSameDay().get(position).getDeliveryTime());
                    tvZitiTime.setText(dataBean.getDeliveryTimeList().getSameDay().get(position).getDeliveryTime());
                    selectTimeLVAdapter.notifyDataSetChanged();
                    select_time_PW.shareClose();
                }
            });
        }
        select_time_PW.showPopupWindow();
    }

    private void showAddress() {
        if (select_address_PW == null) {
            select_address_PW = new ShopCarPopupWindow(this, R.layout.pw_select_address);
            select_address_PW.getRootView().findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    select_address_PW.shareClose();

                }
            });
            select_address_PW.getRootView().findViewById(R.id.tv_bottom).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (Utils.isFastClick()) {
                        //跳转到新增收货地址
                        select_address_PW.shareClose();
                        Intent intent = new Intent(mContext, AddAddressActivity.class);
                        intent.putExtra("from", "confirm");
                        intent.putExtra("is_default", "1");
                        intent.putExtra("id", "");
                        startActivityForResult(intent, START_CODE);
                    }
                }
            });
            llAddressHint = select_address_PW.getRootView().findViewById(R.id.ll_hint);
            rv_address = select_address_PW.getRootView().findViewById(R.id.rv_address);
            rv_address.setLayoutManager(new LinearLayoutManager(this));
            rv_address.setItemAnimator(new DefaultItemAnimator());
            selectAddressRetailAdapter = new SelectAddressRetailAdapter(this, addressList, select_address_PW, mPresenter);
            selectAddressRetailAdapter.setOnItemClickListener(new ItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    if (rlUserAddress.getVisibility() == View.GONE) {
                        llSelectAddress.setVisibility(View.GONE);
                        rlUserAddress.setVisibility(View.VISIBLE);
                    }
                    select_address_PW.shareClose();
                    dataAddressInfo = addressList.get(position);
                    address_id = dataAddressInfo.getId() + "";
                    tvAddressTag.setVisibility(View.VISIBLE);
                    if (dataAddressInfo.getLabel() == 1) {
                        tvAddressTag.setText("家");
                    } else if (dataAddressInfo.getLabel() == 2) {
                        tvAddressTag.setText("公司");
                    } else if (dataAddressInfo.getLabel() == 3) {
                        tvAddressTag.setText("学校");
                    } else {
                        tvAddressTag.setVisibility(View.GONE);
                    }
                    tvAddressInfo.setText(dataAddressInfo.getAddress_info() + dataAddressInfo.getHouse_number());
                    tvUserInfo.setText(dataAddressInfo.getRealname() + "        " + dataAddressInfo.getMobile());
                    ettPhone.setText(dataAddressInfo.getMobile());

                    isCanSubmitOrder = false;
                    submitOrderErrorMessage = "网络错误，请重新选择地址";
                    mPresenter.logistics(dataAddressInfo.getId() + "", dataBean.getOrderKey());
                    mPresenter.defaultAddress(dataAddressInfo.getId() + "", position);


                }
            });
            rv_address.setAdapter(selectAddressRetailAdapter);
        }

    }


    private void default_ziti() {
        tvBigDistribution.setVisibility(View.INVISIBLE);
        tvBigZiti.setVisibility(View.VISIBLE);

        rlUserAddress.setVisibility(View.GONE);
        llSelectAddress.setVisibility(View.GONE);

        llDeliveryTime.setVisibility(View.GONE);
        rlShopZiti.setVisibility(View.VISIBLE);
    }

    @Override
    public void showLoading() {
        ProgressDialog.getInstance().show(this);
    }

    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();
    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void onInitAddressSuccess(AddressListBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            addressList.clear();
            addressList.addAll(bean.getData());
            if (addressList.size() == 0) {
                llAddressHint.setVisibility(View.VISIBLE);
            } else {
                llAddressHint.setVisibility(View.GONE);
            }
            selectAddressRetailAdapter.notifyDataSetChanged();
            select_address_PW.showPopupWindow();
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }

    }


    @Override
    public void onLogisticsSuccess(LogisticsBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            isCanSubmitOrder = bean.getData().getPrice().isIs_can_submit_order();
            submitOrderErrorMessage = bean.getData().getPrice().getSubmit_order_error_message();
            //tvWeightText.setText(dataBean.getPriceGroup().getLogistics_desc().getWeight_text());
            //tvDistance.setText(dataBean.getPriceGroup().getLogistics_desc().getKilometre_text());
//            tvBaseMoney.setText("¥" + bean.getData().getPrice().getBasicFreight());
//            tvWeightMoney.setText("¥" + bean.getData().getPrice().getWeight_price());
//            tvDistanceMoney.setText("¥" + bean.getData().getPrice().getKilometre_price());
            //tvTotalFreight.setText("¥" + bean.getData().getPrice().getStorePostage());

            tvTotalFreight.setText("¥" + (Double.parseDouble(bean.getData().getPrice().getBasicFreight()) +
                    Double.parseDouble(bean.getData().getPrice().getKilometre_price())));
            paymentPrice = "¥" + bean.getData().getPrice().getPaymentPrice();
            tvPayTotalMoney.setText(paymentPrice);
            tvTotalMoney.setText("实付:" + paymentPrice);
            tv_basefee.setText("基础运费" + dataBean.getPriceGroup().getBasicFreight() + "元");
            tv_deslogic.setText(dataBean.getPriceGroup().getLogistics_desc().getKilometre_text());
            tv_desweight.setText(dataBean.getPriceGroup().getLogistics_desc().getWeight_text());
            tv_desorerweight.setText(dataBean.getPriceGroup().getLogistics_desc().getOver_weight_price());
            if (Double.parseDouble(dataBean.getPriceGroup().getWeight_price()) > 0) {
                rl_desover.setVisibility(View.VISIBLE);
                //超重费
                tv_orerweight_fee.setText("¥" + dataBean.getPriceGroup().getWeight_price());
            } else {
                rl_desover.setVisibility(View.GONE);
            }
        } else {
            Utils.toastMessage(mContext, bean.getMsg());
        }

    }

    @Override
    public void onConfirmOrderSuccess(NewOrderBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            //刷新购物车零售列表
            EventBus.getDefault().post(new CarInitDataMessage(0));
            tvToPay.setEnabled(false);
            if (pay_type.equals("weixin")) {
                boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
                if (isPaySupported) {
                    PayReq req = new PayReq();
                    req.appId = bean.getData().getResult().getJsConfig().getAppid();
                    req.partnerId = bean.getData().getResult().getJsConfig().getPartnerid();
                    req.prepayId = bean.getData().getResult().getJsConfig().getPrepayid();
                    req.nonceStr = bean.getData().getResult().getJsConfig().getNoncestr();
                    req.timeStamp = bean.getData().getResult().getJsConfig().getTimestamp() + "";
                    req.packageValue = bean.getData().getResult().getJsConfig().getPackageX();
                    req.sign = bean.getData().getResult().getJsConfig().getSign();
                    req.extData = "";
                    api.sendReq(req);
                } else {
                    Toast.makeText(this, "当前微信版本不支持支付", Toast.LENGTH_SHORT).show();
                }
            } else if (pay_type.equals("alipay")) {
                final Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(ConfirmOrderActivity.this);
                        Map<String, String> result = alipay.payV2(bean.getData().getResult().getAlipay_param(), true);
                        Log.i("msp", result.toString());

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            } else if (pay_type.equals("abcp")) {
/**
 * 判断手机上是否具备调起农行掌银的条件
 */
                if (BankABCCaller.isBankABCAvaiable(ConfirmOrderActivity.this)) {

                    /**
                     * 调起农行掌银
                     */
//                    BankABCCaller.startBankABC(ConfirmOrderActivity.this, "cn.xfdzx.android.apps.shop", "cn.xfdzx.android.apps.shop.activity.ConfirmOrderActivity", "pay", bean.getData().getResult().getAbcApp());
                    BankABCCaller.startBankABC(ConfirmOrderActivity.this, "cn.xfdzx.android.apps.shop", "cn.xfdzx.android.apps.shop.activity.ConfirmOrderActivity", "pay", bean.getData().getResult().getAbcApp());
                } else {//客户手机未安装农行掌银APP的处理逻辑，由第三方APP自行实现
                    tvToPay.setEnabled(true);
                    Toast.makeText(ConfirmOrderActivity.this, "没安装农行掌银，或已安装农行掌银版本不支持", Toast.LENGTH_LONG).show();
                }
                return;

            }

            tvToPay.setEnabled(true);

        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }

    }

//    支付宝跳转链接 if (true){
//                    if (openAlipayPayPage(this,bean.getData().getResult().getAlipay())){
//                        Utils.toastMessage(this,"跳转成功");
//                    }else {
//                        Utils.toastMessage(this,"未能打开支付宝，请手动打开");
//                    }
//                    return;
//                }
//    public static boolean openAlipayPayPage(Context context,String text) {
//        try {
//            // final String alipayqr = "alipayqr://platformapi/startapp?saId=10000001&clientVersion=3.7.0.0718";
////            final String alipayqr = "alipayqr://platformapi/startapp?clientVersion=3.7.0.0718";
//            final String alipayqr = "alipays://platformapi/startapp?appId=20000067&url="+text;
//            openUri(context, alipayqr);
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return false;
//    }
//
//    /**
//     * 发送一个intent
//     */
//    private static void openUri(Context context, String s) {
//        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(s));
//        context.startActivity(intent);
//    }

    @Override
    public void onDelectSuccess(DeleteAddressBeen bean, int position) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (address_id.equals(addressList.get(position).getId() + "")) {
                rlUserAddress.setVisibility(View.GONE);
                llSelectAddress.setVisibility(View.VISIBLE);
                address_id = "";
            }
            addressList.remove(position);
            rv_address.closeMenu();
            selectAddressRetailAdapter.notifyDataSetChanged();
        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(this, "login").remove("head_url");
                UtilsData.getPreference(this, "login").remove("nickname");
                UtilsData.getPreference(this, "login").remove("is_store");
                UtilsData.getPreference(this, "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(this, OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDefaultSuccess(DeleteAddressBeen bean, int position) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            addressList.clear();
        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(this, "login").remove("head_url");
                UtilsData.getPreference(this, "login").remove("nickname");
                UtilsData.getPreference(this, "login").remove("is_store");
                UtilsData.getPreference(this, "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(this, OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == START_CODE) {
                if (rlUserAddress.getVisibility() == View.GONE) {
                    llSelectAddress.setVisibility(View.GONE);
                    rlUserAddress.setVisibility(View.VISIBLE);
                }
                addressList.clear();
                dataAddressInfo = (AddressListBeen.DataBean) data.getSerializableExtra("data");
                address_id = dataAddressInfo.getId() + "";
                tvAddressTag.setVisibility(View.VISIBLE);
                if (dataAddressInfo.getLabel() == 1) {
                    tvAddressTag.setText("家");
                } else if (dataAddressInfo.getLabel() == 2) {
                    tvAddressTag.setText("公司");
                } else if (dataAddressInfo.getLabel() == 3) {
                    tvAddressTag.setText("学校");
                } else {
                    tvAddressTag.setVisibility(View.GONE);
                }
                tvAddressInfo.setText(dataAddressInfo.getAddress_info() + dataAddressInfo.getHouse_number());
                tvUserInfo.setText(dataAddressInfo.getRealname() + "        " + dataAddressInfo.getMobile());
                ettPhone.setText(dataAddressInfo.getMobile());

                isCanSubmitOrder = false;
                submitOrderErrorMessage = "网络错误，请重新选择地址";
                mPresenter.logistics(address_id + "", dataBean.getOrderKey());
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (select_address_PW != null) {
            if (select_address_PW.isShowing()) {
                select_address_PW.shareClose();
                return;
            }
        }
        if (select_time_PW != null) {
            if (select_time_PW.isShowing()) {
                select_time_PW.shareClose();
                return;
            }
        }
        if (select_out_stock_PW != null) {
            if (select_out_stock_PW.isShowing()) {
                select_out_stock_PW.shareClose();
                return;
            }
        }
        if (couponPopupWindow != null) {
            if (couponPopupWindow.isShowing()) {
                couponPopupWindow.shareClose();
                return;
            }
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        selectMaps.clear();
        if (select_address_PW != null) {
            if (select_address_PW.isShowing()) {
                select_address_PW.dismiss();
            }
            select_address_PW = null;
        }
        if (select_time_PW != null) {
            if (select_time_PW.isShowing()) {
                select_time_PW.dismiss();
            }
            select_time_PW = null;
        }
        if (select_out_stock_PW != null) {
            if (select_out_stock_PW.isShowing()) {
                select_out_stock_PW.dismiss();
            }
            select_out_stock_PW = null;
        }
        if (couponPopupWindow != null) {
            if (couponPopupWindow.isShowing()) {
                couponPopupWindow.dismiss();
            }
            couponPopupWindow = null;
        }
        if (dialog_note.isShowing()) {
            dialog_note.dismiss();
        }
//        if (dialog_peisong.isShowing()) {
//            dialog_peisong.dismiss();
//        }
        map.onDestroy();
        super.onDestroy();
    }

    /**
     * 添加软键盘监听
     */
    private void setSoftKeyBoardListener() {
        SoftKeyBoardListener softKeyBoardListener = new SoftKeyBoardListener(this);
        //软键盘状态监听
        softKeyBoardListener.setListener(new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                //软键盘已经显示，做逻辑

            }

            @Override
            public void keyBoardHide(int height) {
                //软键盘已经隐藏,做逻辑
                ettPhone.setEnabled(false);
            }
        });
    }

    private static final int SDK_PAY_FLAG = 1;

    Intent intent;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        if (IS_FORM){
//                            IS_FORM=false;
//                        }
                        intent = new Intent(mContext, MainActivity.class);
                        intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
                        intent.addFlags(FLAG_ACTIVITY_SINGLE_TOP);
                        intent.putExtra("from", "pay");
                        startActivity(intent);
                        break;
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        if (IS_FORM){
//                            IS_FORM=false;
//                            finish();
//                        }else {
                        intent = new Intent(mContext, MainActivity.class);
                        intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
                        intent.addFlags(FLAG_ACTIVITY_SINGLE_TOP);
                        intent.putExtra("from", "pay_cancel");
                        startActivity(intent);
//                        }

                    }

                    break;
                }

                default:
                    break;
            }
        }

        ;
    };

}
